-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		vanduong
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE spKeHoach_KiemTraChiTieu 
	@NAM_KE_HOACH_ID int,
	@DON_VI_ID int
AS
BEGIN
	declare @KEHOACH Table(
	[ID] int,
	DON_VI_ID int,
	[CHI_TIEU_ID] int
)
declare @DONVI_CHITIEU Table(
	ID int,
	DON_VI_ID int,
	[CHI_TIEU_ID] int
)

declare @R3 Table(
	ID int,
	DON_VI_ID int,
	[CHI_TIEU_ID] int,
	DonViId int,
	ChiTieuId int
)

	insert into @KEHOACH
	SELECT ID, DON_VI_ID, [CHI_TIEU_ID]
	FROM [NV].[KEHOACH]
	WHERE [NAM_KE_HOACH_ID] = @NAM_KE_HOACH_ID and STATUS_ID=10 and 
	[CHI_TIEU_ID] in (select [CHI_TIEU_ID] from [NV].[DONVI_CHITIEU] 
	where [NAM_KE_HOACH_ID] = @NAM_KE_HOACH_ID and [DON_VI_ID]  = @DON_VI_ID and FLAG = 1)
	order by CHI_TIEU_ID

	insert into @DONVI_CHITIEU
	SELECT DON_VI_CHI_TIEU_ID as ID, DON_VI_ID, [CHI_TIEU_ID]
		FROM [NV].[DONVI_CHITIEU]
		where [NAM_KE_HOACH_ID]  = @NAM_KE_HOACH_ID and [FLAG] = 0 and
		[DON_VI_ID] in (Select [DON_VI_ID] from [DM].[DONVI] 
			where [CO_QUYEN_GIAM_SAT] = 0 or [CO_QUYEN_GIAM_SAT] = 2)
		and  [CHI_TIEU_ID] in (select [CHI_TIEU_ID] from [NV].[DONVI_CHITIEU]
		 where [NAM_KE_HOACH_ID] = @NAM_KE_HOACH_ID and [DON_VI_ID]  = @DON_VI_ID and FLAG = 1)
			order by CHI_TIEU_ID

	insert into @R3 
	select t.ID, t.DON_VI_ID, t.CHI_TIEU_ID, 
		d.DON_VI_ID as DonViId, d.CHI_TIEU_ID as ChiTieuId
	 from @DONVI_CHITIEU t left join @KEHOACH d
	on t.DON_VI_ID = d.DON_VI_ID and 
	t.CHI_TIEU_ID = d.CHI_TIEU_ID

	select t.ID, 
		t.DON_VI_ID, 
		t.CHI_TIEU_ID,
		d.DON_VI,
		c.TEN_CHI_TIEU
		from @R3 t join [DM].[DONVI] d
		on t.DON_VI_ID = d.DON_VI_ID 
		join [DM].[CHITIEU] c 
		on t.CHI_TIEU_ID = c.CHI_TIEU_ID
	where DonViId is null and ChiTieuId is null
END
GO
